package com.ffs.lock;

import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 持有者
 *
 * @author ffs80 created 2021/7/2
 */
public class Holder {

    private final Class<?> clazz;
    /**
     * 重入锁
     */
    private final ReentrantLock tieLock = new ReentrantLock();

    private final Map<Object, ObjectLock> locks = Collections.synchronizedMap(new WeakHashMap<>());
    /**
     * 读写锁
     */
    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();


    public Holder(Class<?> clazz) {
        this.clazz = clazz;
    }

    public ObjectLock getLock(Object object) {
        Lock lock = this.lock.readLock();
        try {
            lock.lock();
            ObjectLock result = this.locks.get(object);
            if (result != null) {
                ObjectLock localObjectLock = result;
                return localObjectLock;
            }
        } finally {
            lock.unlock();
        }
        return createLock(object);
    }

    private ObjectLock createLock(Object object) {
        Lock lock = this.lock.writeLock();
        try {
            lock.lock();
            ObjectLock result = this.locks.get(object);
            if (result != null) {
                return result;
            }
            result = new ObjectLock(object);
            this.locks.put(object, result);
            return result;
        } finally {
            lock.unlock();
        }
    }

    public ReentrantLock getTieLock() {
        return this.tieLock;
    }

    public int count() {
        return this.locks.size();
    }

}
